package com.jdz.interceptor;

import com.google.gson.Gson;
import com.jdz.common.Const;
import com.jdz.common.ResponseCode;
import com.jdz.common.ServerResponse;
import com.jdz.service.IUserService;
import com.jdz.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    IUserService iUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //获取请求的url
        String url = request.getRequestURL().toString();
        //判断url是否是公开 地址（实际使用时将公开 地址配置配置文件中）//这里公开地址是登陆提交的地址if(url.indexOf("login.action")>=0){
        //如果进行登陆提交，放行returntrue;

        HttpSession session = request.getSession();

        UserVo userVo = (UserVo) session.getAttribute(Const.CURRENT_USER);
        if(userVo == null){
            PrintWriter out = null ;
            try{
                Gson gson = new Gson();

                String json = null;

                if(url.indexOf("manage")>=0){
                    json = gson.toJson(ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"管理员未登录,请登录"));
                }else {
                    json = gson.toJson(ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录"));
                }


                response.setHeader("Content-Type","application/json;charset=UTF-8");
                out = response.getWriter();

                out.append(json);
                out.close();
                return false;
            }catch (Exception e) {
                e.printStackTrace();
                response.sendError(500);
                return false;
            }
        }
        System.out.println("2");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
